package cn.wolfcode.luowowo.website.resolver;

import cn.wolfcode.luowowo.cache.service.IUserInfoCacheService;
import cn.wolfcode.luowowo.common.util.Consts;
import cn.wolfcode.luowowo.website.annotation.LoginUser;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

@Component
public class UserInfoArgumentResolver implements HandlerMethodArgumentResolver {
    @Reference
    private IUserInfoCacheService userInfoCacheService;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        if (parameter.hasParameterAnnotation(LoginUser.class)) {
            return true;
        }
        return false;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        //得到当前请求对象
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        //获取session,类里面有就直接返回
        Object userInfo = request.getSession().getAttribute(Consts.USER_INFO);
        if (userInfo != null) {
            return userInfo;
        }
        //注意判断不为null避免空指针
        if (request.getCookies() != null) {
            //获取cookie的token去redis查
            for (Cookie cookie : request.getCookies()) {
                if (Consts.USER_INFO_TOKEN.equals(cookie.getName())) {
                    String info = userInfoCacheService.getUserInfo(Consts.USER_INFO_TOKEN);
                    request.getSession().setAttribute(Consts.USER_INFO, info);
                    return info;
                }
            }
        }
        return null;
    }
}
